﻿using System;
using System.Configuration;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http;
using Newtonsoft.Json.Serialization;
using Sustainalytics.DataLayer.ConnectionStrings;
using Sustainalytics.Entities.ConnectionStrings;
using Sustainalytics.Utils.WebApi.Filters;

namespace Sustainalytics.ESGRatings.Service
{


    public static class ClientPlatform
    {
        public static string GetConnectionString()
        {
            return ConfigurationManager.ConnectionStrings["ClientPlatform"].ConnectionString;
        }
    }

    public static class ClientDWConnection
    {
        public static string GetConnectionString()
        {
            var clientConnectionString = ConfigurationManager.ConnectionStrings["ClientPlatform"].ConnectionString;
            var connectionStringsManager =
                ConnectionStringsManager.GetInstance(ConnectionStringsRepository.GetInstance(clientConnectionString));
            return connectionStringsManager.GetConnectionString(ConnectionStringType.ClientDW);
        }
    }

    public static class HistoryDWConnection
    {
        public static string GetConnectionString()
        {
            var clientConnectionString = ConfigurationManager.ConnectionStrings["ClientPlatform"].ConnectionString;
            var connectionStringsManager =
                ConnectionStringsManager.GetInstance(ConnectionStringsRepository.GetInstance(clientConnectionString));
            return connectionStringsManager.GetConnectionString(ConnectionStringType.DWArchive);
        }
    }

    static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            bool.TryParse(ConfigurationManager.AppSettings["enableCors"], out bool allowCors);
            if (allowCors)
                config.EnableCors();

            bool useHttps;
            bool.TryParse(ConfigurationManager.AppSettings["UseHttps"], out useHttps);

            if (useHttps)
            {
                // Force HTTPS on entire API
                config.Filters.Add(new RequireHttpsAttribute());
            }

            //use camel case for json not default pascal case from .NET
            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            //all routing will be done through route attributes inside controllers
            config.MapHttpAttributeRoutes();

            config.Filters.Add(new CacheabilityActionFilterAttribute());

            config.EnsureInitialized();

        }
    }
}
